﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Xml.Linq;
using System.Web.Caching;
using Aandelendelen.Caching;
using Aandelendelen.Obs;

namespace Aandelendelen.Stocks
{
	public class StockIDCollection : Dictionary<string, int>, ICacheable
	{
		public static string CacheName = "data_stockids"; 

		public Dictionary<int, string> StocksById { get; private set; }

		public StockIDCollection()
			: base(64)
		{
			this.InitCacheKey();

			this.StocksById = new Dictionary<int, string>(64);

			XDocument doc = XDocument.Load(HttpContext.Current.Server.MapPath("/App_Data/StockID.xml"));

			foreach (XElement elt in doc.Elements().First<XElement>().Elements("stock"))
			{
				XAttribute attrId = elt.Attributes("id").First<XAttribute>();
				XAttribute attrName = elt.Attributes("name").First<XAttribute>();

				int id = Convert.ToInt32(attrId.Value);

				this[attrName.Value] = id;
				this.StocksById[id] = attrName.Value;
			}
		}

		public static StockIDCollection GetInstance()
		{
			return DataCache.GetCacheableObject<StockIDCollection>(CacheName);
		}

		public static StockIDCollection GetInstance(string cacheKey)
		{
			return DataCache.GetCacheableObject<StockIDCollection>(cacheKey);
		}

		#region ICacheable
		public CacheKey CacheKey { get; set; }

		public void CacheThis(string cacheKey)
		{
			this.CacheKey.CacheThis(cacheKey);
		}

		public void InitCacheKey()
		{
			CacheKey = new CacheKey()
			{
				CacheDependency = new CacheDependency(HttpContext.Current.Server.MapPath("/App_Data/StockID.xml")),
				ObjectToCache = this
			};
		}
		#endregion

	}
}